package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseOrderSaleDetailFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.OderSaleContent;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;

public class ShowOrderSaleDeatilFragment extends BaseOrderSaleDetailFragment {
  public static final String EXTRA_CONTENT = "com.isunland.managesystem.entity.EXTRA_CONTENT";
  private OderSaleContent mContent;

  @Override public void onCreate(Bundle savedInstanceState) {
    mContent = (OderSaleContent) getArguments().getSerializable(EXTRA_CONTENT);
    super.onCreate(savedInstanceState);
  }

  @Override protected void setTitle() {
    //noinspection ConstantConditions
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle("订单明细");
  }

  @Override protected void initOrderData() {
    tvCustomerCompany.setText(mContent.getMcustomerName());
    etCustomerApartment.setText(mContent.getMcustomerDeptName());
    etCustomerApartment.setEnabled(false);
    etMainProduct.setText(mContent.getMoutCom());
    etMainProduct.setEnabled(false);
    tvMaterialKind.setText(mContent.getMaterialKindName());//出库物料类别
    tvWarehouse.setText(mContent.getStorageName());// 出货仓库
    tvSalePerson.setText(mContent.getMoutappmanName());// 销售业务员
    tvOutNotes.setText(mContent.getMoutbillNo());// 出库单编号
    tvRegisteredErson.setText(mContent.getRegStaffName());// 登记人
    tvRegisteredTime.setText(mContent.getRegDate());// 登记时间
    if ("new".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.draft);// 数据状态草稿
    } else if ("checkPass".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.hasAudited);// 数据状态已提交
    } else if ("outStock".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.already_out);// 数据状态已出库
    } else if ("waitCheck".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.checking);// 数据状态审核中
    } else if ("abort".equals(mContent.getMoutbillStatus())) {
      tvDataStatus.setText(R.string.stopup);// 数据状态终止
    } else {
      tvDataStatus.setText(R.string.errData);// 数据状态已出库
    }

    tvHandlePrson.setText(mContent.getMoutdealmanName());// 办理人
    tvHandleTime.setText(mContent.getMoutdealDate());// 办理时间
    etNotes.setText(mContent.getRemark());// 备注
    etNotes.setEnabled(false);

    ibCustomerCompany.setVisibility(View.GONE);
    ibMaterialKind.setVisibility(View.GONE);
    ibSalePerson.setVisibility(View.GONE);
    ibWarehouse.setVisibility(View.GONE);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_order_sale, menu);

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      // 回退键
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;
      // 编辑修改界面
      case R.id.menu_item_alter:
        // 如果登记人是当前登录人

        if ("new".equals(mContent.getMoutbillStatus()) || "abort".equals(
            mContent.getMoutbillStatus())) {
          Intent i = new Intent(getActivity(), EditeOrderSaleDetailActivity.class);
          i.putExtra(EditOrderSaleDeatilFragment.EXTRA_CONTENT, mContent);
          startActivityForResult(i, EDITE_ORDER);
        } else {
          ToastUtil.show(R.string.draftOrAbort);
        }

        break;
      // 删除
      case R.id.menu_item_delete:

        if ("new".equals(mContent.getMoutbillStatus()) || "abort".equals(
            mContent.getMoutbillStatus())) {

          showDialog(DELETE_ORDER);
        } else {
          ToastUtil.show(R.string.draftOrAbort);
        }

        break;
      // 启动流程
      case R.id.menu_item_submit:
        if ((mContent.getRegStaffId()).equals(mCurrentUser.getJobNumber())) {
          if ("new".equals(mContent.getMoutbillStatus()) || "abort".equals(
              mContent.getMoutbillStatus())) {
            //					volleyPostSubmit();
            showDialog(SUBMIT_ORDER);
          } else {
            ToastUtil.show(R.string.ifstartup);
          }
        } else {
          ToastUtil.show(R.string.ifstartup);
        }
        break;
      // 终止流程
      case R.id.menu_item_noSubmit:
        if ((mContent.getRegStaffId()).equals(mCurrentUser.getJobNumber())) {
          if ("checkPass".equals(mContent.getMoutbillStatus()) || DataStatus.WAIT_CHECK.equals(
              mContent.getMoutbillStatus())) {
            //					volleyPostNoSubmit();
            showDialog(NO_SUBMITE_ORDER);
          } else {
            ToastUtil.show(R.string.no_restart);
          }
        } else {
          ToastUtil.show(R.string.name_false);
        }
        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  // 取消提交
  private void volleyPostNoSubmit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_NOSUBMI_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("status", "abort");
    params.put("ids", mContent.getId() + ",");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, volleyResponse());
  }

  // 终止流程
  private void volleyPostAbort() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();
    params.put("runId", mContent.getRunId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, volleyResponse());
  }

  // 提交
  private void volleyPostSubmit() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SUBMIT_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("ifSaleOrder", "true");
    params.put("id", mContent.getId());
    LogUtil.i("启动流程===" + params.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, volleyResponse());
  }

  // 删除
  private void vollePostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_SAVE_ORDER);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mContent.getId());

    HashMap<String, String> mParams = new HashMap<>();
    mParams.put("deleted", "[" + new JSONObject(params).toString() + "]");
    LogUtil.i("delete===" + mParams.toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, mParams, volleyResponse());
  }

  public VolleyResponse volleyResponse() {
    return new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          LogUtil.i("response=" + arg0);
          MyUtils.dismissDialog();
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == success || null == success.getResult()) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          String successType = success.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();

            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
      }
    };
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == EDITE_ORDER) {
      getActivity().setResult(Activity.RESULT_OK);
      getActivity().finish();
    }
    // 删除
    if (requestCode == DELETE_ORDER) {
      vollePostDelete();
    }
    // 提交
    if (requestCode == SUBMIT_ORDER) {
      volleyPostSubmit();
    }
    // 终止流程
    if (requestCode == NO_SUBMITE_ORDER) {

      if (DataStatus.CHECK_PASS.equals(mContent.getMoutbillStatus())) {
        volleyPostNoSubmit();
      }
      if (DataStatus.WAIT_CHECK.equals(mContent.getMoutbillStatus())) {
        volleyPostAbort();
      }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  public static ShowOrderSaleDeatilFragment newInstance(OderSaleContent item) {
    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, item);
    ShowOrderSaleDeatilFragment fragment = new ShowOrderSaleDeatilFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
